import { BaseSubscriber } from "src/database/base/subscriber";
import { EventSubscriber, InsertEvent, ObjectType, UpdateEvent } from "typeorm";
import { UserEntity } from "./entity/user.entity";
import { randomBytes } from "node:crypto";
import { isNil } from 'lodash';
import { encrypt } from "./helper";

@EventSubscriber()
export class UserSubscriber extends BaseSubscriber<UserEntity>{
    protected entity: ObjectType<UserEntity>;
    /* 生成不重复的随机的用户名 */
    protected async generateUserName(event:InsertEvent<UserEntity>){
    const username=`user_${randomBytes(4).toString('hex').slice(0,8)}`
    const user=await event.manager.createQueryBuilder().where({username})
      return isNil(user)? username:this.generateUserName(event)
    }

    //自动 生成唯一用户名 和密码
    async beforeInsert(event:InsertEvent<UserEntity>){
        if(!event.entity.username){
           event.entity.username=this.generateUserName(event)
        }
        if(!event.entity.password){
            event.entity.password=`password_${randomBytes(4).toString('hex').slice(0,10)}`
        }
        //自动加密密码
        event.entity.password = await encrypt(event.entity.password);
    }

     /**
     * 当密码更改时加密密码
     * @param event
     */
     async beforeUpdate(event: UpdateEvent<UserEntity>) {
        if (this.isUpdated('password', event)) {
            event.entity.password = encrypt(event.entity.password);
        }
    } 
}
